/**
 * Description:
 * Class Name:BlobTest
 * Date:2022/4/10 11:05
 *
 * @author LTisme
 * @version JAVA17
 */
package 疯狂Java讲义.第13章_MySQL数据库和JDBC编程._13_5_管理结果集._13_5_2_处理Blob类型的数据;

import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.Properties;

/**
 * 这里不像作者一样做一个显示图片的窗口，这里只实现将图片插入进数据库中，然后用select查看结果
 */
public class BlobTest {
    private String driver;
    private String url;
    private String user;
    private String pwd;

    public void initParam(String paramFilePath) throws Exception{
        Properties props = new Properties();
        props.load(new FileInputStream(paramFilePath));
        driver = props.getProperty("driver");
        url = props.getProperty("url");
        user = props.getProperty("user");
        pwd = props.getProperty("pwd");
    }

    public void insertBlob(String sql, String image_path) throws Exception{
        try (
                Connection connection = DriverManager.getConnection(url, user, pwd);
                PreparedStatement ps = connection.prepareStatement(sql);
                ){
            ps.setString(1, "cmd命令截图");
            ps.setBinaryStream(2, new FileInputStream(image_path));

            // 执行插入数据
            int affect = ps.executeUpdate();
            if (affect == 1){   // 如果有一行受影响，则说明插入成功
                System.out.println("执行Blob插入成功");
            }
            else {
                System.out.println("执行Blob插入失败");
            }
        }
    }

    public static void main(String[] args) throws Exception{
        var bt = new BlobTest();
        bt.initParam("Chapter_13_mysql.ini");
        Class.forName(bt.driver);

        String sql_for_insert_blob = "insert into image_table(image_name, image)" +
                " values " +
                "(?, ?)";
        // 先用未在MySQL权限目录中的图片路径尝试一下，发现可以破除对MySQL的权限目录的限制
        String image_path_for_insert_blob = "D:\\Java_Practice_Files\\疯狂java学习笔记的图片库\\idea_external_libararies.png";
        // 再用在MySQL权限目录中的图片路径尝试一下
        String image_path_for_insert_blob2 = "D:\\MySQL_Installation\\Data_Directory\\Uploads\\JDBC_cmd.png";

        bt.insertBlob(sql_for_insert_blob, image_path_for_insert_blob);
    }
}
